package com.hontech.libratest.activity.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.hontech.libratest.R
import com.hontech.libratest.activity.fragment.sub.FirmSub
import com.hontech.libratest.conn.Device
import com.hontech.libratest.env.DeviceEvent
import com.hontech.libratest.model.DeviceStatus
import com.hontech.libratest.utils.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class SettingFragment : Fragment() {

    private lateinit var mBtnOpen: Button
    private lateinit var mTvVersion: TextView
    private lateinit var mEtAddr: EditText
    private lateinit var mTvAppVersion: TextView

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_setting, null)
        init(view)
        return view
    }

    private fun init(view: View) {
        mBtnOpen = view.findViewById(R.id.id_setting_btn_port_open)
        mTvVersion = view.findViewById(R.id.id_setting_tv_version)
        mEtAddr = view.findViewById(R.id.id_setting_et_addr)
        mBtnOpen.setOnClickListener(onClickOpen)
        mTvAppVersion = view.findViewById(R.id.id_setting_tv_app_version)

        mTvAppVersion.text = Version

        FirmSub(view)
    }

    private val onClickOpen = fun(_: View) {
        if (Device.openFlag) {
            Device.close()
            mBtnOpen.text = "打开串口"
            return
        }

        try {
            Device.destAddr = mEtAddr.toInt()
        } catch (e: Exception) {
            e.printStackTrace()
            showToast("请输入设备地址")
        }

        Device.open {
            if (it) {
                mBtnOpen.text = "关闭串口"
            } else {
                showToast("串口打开失败")
            }
        }
    }

    override fun onStart() {
        super.onStart()
        eventBus.register(this)
    }

    override fun onStop() {
        super.onStop()
        eventBus.unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onDeviceEvent(env: DeviceEvent) {
        val status = DeviceStatus.instance
        mTvVersion.text = "${status.appVersion.value.toHexStr4()}"
    }

}

